package io.github.kuafucv.zero.log.helper.system;

import java.io.Serializable;
import java.net.InetAddress;

public class HostInfo implements Serializable {

	private static final long serialVersionUID = 1L;

	private final String HOST_NAME;
	private final String HOST_ADDRESS;
	private static volatile HostInfo instance;

	public static HostInfo buildInstance() {
		if(instance == null) {
			synchronized (HostInfo.class) {
				if(instance == null) {
					instance = new HostInfo();
				}
			}
		}
		return instance;
	}

	private HostInfo() {
		InetAddress localhost = null;
		try{
			localhost = SystemHelper.getLocalAddress();
		}catch (Exception ignored) {}
		String hostname = null;
		try {
			hostname = System.getenv("hostname");
			if(hostname == null || hostname.isEmpty()) {
				hostname = System.getenv("HOSTNAME");
			}
			if(hostname == null || hostname.isEmpty()) {
				InetAddress inetAddress = InetAddress.getLocalHost();
				hostname = inetAddress.getHostName();
			}
		} catch (Exception ignored) {
		}
		HOST_NAME = hostname;
		if(null != localhost){
			HOST_ADDRESS = localhost.getHostAddress();
		} else{
			HOST_ADDRESS = null;
		}
	}

	/**
	 * 取得当前主机的名称。
	 *
	 * <p>
	 * 例如：<code>"webserver1"</code>
	 * </p>
	 *
	 * @return 主机名
	 */
	public final String getName() {
		return HOST_NAME;
	}

	/**
	 * 取得当前主机的地址。
	 *
	 * <p>
	 * 例如：<code>"192.168.0.1"</code>
	 * </p>
	 *
	 * @return 主机地址
	 */
	public final String getAddress() {
		return HOST_ADDRESS;
	}

	@Override
	public String toString() {
		return "HostInfo{" +
				"HOST_NAME='" + HOST_NAME + '\'' +
				", HOST_ADDRESS='" + HOST_ADDRESS + '\'' +
				'}';
	}

}
